<template>
  <a-modal
    width="700px"
    :bodyStyle="{ height: '600px' }"
    title="文书类型选择"
    :visible="modalVisible"
    :footer="null"
    @cancel="closeModal"
  >
    <a-spin size="large" :spinning="spinning">
      <div>
        <a-input-search
          v-model="searchValue"
          style="margin-bottom: 8px;width: 70%"
          placeholder="搜索"
          @change="searchTreeNode"
        />
        <a-button type="primary" style="float:right; margin-right: 60px;" @click="handleConfirm">确认</a-button>
      </div>
      <div style="overflow:auto;height:500px">
        <a-tree
          ref="treeRef"
          :key="treeRefKey"
          :tree-data="treeData"
          default-expand-all
          show-icon
          @select="onSelect"
          :defaultCheckedKeys="defaultKeys"
          @check="onCheck"
          :expanded-keys="expandedKeys"
          :auto-expand-parent="false"
          @expand="onExpand"
          checkable
          class="tree-div-select-hidden"
        >
          <template slot="custom" slot-scope="item">
            <div v-if="item.level == 0 || item.level == 1" class="algin_justity_center">
              <div v-if="expandedKeys.includes(item.key) " class="custom-icon-fold algin_justity_center">
                －
              </div>
              <div v-else-if="!expandedKeys.includes(item.key) " class="custom-icon-open algin_justity_center">
                ＋
              </div>
              <!-- </div> -->
              <div v-if="item.title.indexOf(searchValue) > -1" class="ant-tree-title-margin">
                {{ item.title.substr(0, item.title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ item.title.substr(item.title.indexOf(searchValue) + searchValue.length) }}
              </div>
              <div v-else class="ant-tree-title-margin">{{ item.title }}</div>
            </div>
            <div v-if="item.level == 2" class="algin_justity_center">
              <!-- <a-icon type="book" /> -->
              <div v-if="expandedKeys.includes(item.key) " class="custom-icon-fold algin_justity_center">
                －
              </div>
              <div v-else-if="!expandedKeys.includes(item.key) " class="custom-icon-open algin_justity_center">
                ＋
              </div>
              <span v-if="item.title.indexOf(searchValue) > -1" class="ant-tree-title-margin">
                {{ item.title.substr(0, item.title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ item.title.substr(item.title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else class="ant-tree-title-margin">{{ item.title }}</span>
              <span style="margin-left: 20px;color:#0072c6"> 文件数量：{{ item.children ? item.children.length: 0 }}</span>
              <!-- <a-badge :count="item.children ? item.children.length: 0" :number-style="{ backgroundColor: '#0072c6' }" /> -->
              <span class="but_operation" style="margin-left: 50px">
                <span class="but_type" @click="uploadModalShow(item)">新增</span>
                <!-- <a-upload
                  :accept="acceptFileType"
                  :customRequest="uploadMaterial"
                  :showUploadList="false"
                  :beforeUpload="file => beforeUpload(file)"
                  name="file"
                  :multiple="true"
                >
                  <span class="but_type" @click="() => addDocument(item)">新增</span>
                </a-upload> -->
              </span>
            </div>
            <div v-if="item.level == 3" class="hover-div algin_justity_center" >
              <a-icon type="file" style="margin-right: 10px;"/>
              <span class="file-tree-content" v-if="item.title.indexOf(searchValue) > -1">
                {{ item.title.substr(0, item.title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ item.title.substr(item.title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span class="file-tree-content" v-else>{{ item.title }}</span>
              <a-tag v-if="item.isSend" color="#87d068" style="font-size: 12px;margin-left: 20px;color: #fff;">
                已送达
              </a-tag>
              <a-icon v-else type="delete" class="hover-delete" @click.stop="deleteFile(item)" />
            </div>
          </template>
          <template slot="switcherIcon" slot-scope="item">
            <div class="icon-add" v-if="item.level == 0" style="opacity: inherit;"></div>
            <div class="icon-add" v-else></div>
          </template>
        </a-tree>
      </div>
    </a-spin>

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>

  </a-modal>
</template>

<script>
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { getDocumentTree } from '@/api/arrive/apl_arrive_details'
import { saveMaterialArrive } from '@/api/accept/aprv_process_materials'
import { kkfilePreview } from '@/utils/util.js'
import { deleteMaterial } from '@/api/accept/aprv_process_materials'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
export default {
  props: {
    applyid: {
      type: String,
      required: true,
      default: ''
    },
    checkObj: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      modalVisible: false,
      acceptFileType: FILETYPE,
      selectBusiType: '',
      treeData: [],
      cloneTreeData: [],
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      treeLevel3Data: [], // 保存文件的树结构
      checkList: [],
      checkItem: {},
      defaultKeys: [],
      searchValue: '', // 搜索值
      spinning: false, // 加载框
      expandedKeys: [], // 展开指定的树节点

      treeRefKey: 0
    }
  },
  components: {
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  computed: {},
  created () {
  },
  methods: {
    init () {
      this.searchValue = ''
      this.queryDocumentTree()
      if (!(this.checkObj && this.checkObj.length > 0)) {
        this.defaultKeys = []
        this.checkList = []
        this.checkItemList = []
        this.treeRefKey++
      }
    },
    closeModal () {
      this.modalVisible = false
    },
    handleConfirm () {
      if (this.checkList.length == 0) {
        this.$message.error('请勾选一条数据')
        return
      } else {
        this.checkItemList = []
        if (this.treeLevel3Data && this.treeLevel3Data.length > 0) {
          this.treeLevel3Data.forEach(item => {
            if (item) {
              this.checkList.forEach(check => {
                if (item.key == check) {
                  this.checkItemList.push(item)
                }
              })
            }
          })
          let comfirmTitle = '是否选择该文件？'
          if (this.checkItemList && this.checkItemList.length > 0) {
            this.checkItemList.forEach(el => {
              if (el.isSend) {
                comfirmTitle = '该文件已送达，是否选择该文件？'
              }
            })
          }
          this.$confirm({
            title: comfirmTitle,
            onOk: () => {
              this.modalVisible = false
              this.$emit('setFileInfo', this.checkItemList)
            }
          })
        }
      }
    },
    getCheckedData () {
      if (this.treeLevel3Data == null || this.treeLevel3Data.length == 0) {
        this.findLevel3Data()
      }
      if (this.treeLevel3Data && this.treeLevel3Data.length > 0) {
        this.treeLevel3Data.forEach(item => {
          if (item.document.file) {
            if (this.checkObj && this.checkObj.length > 0) {
              this.checkObj.forEach(el => {
                if (el.attachid && (item.document.file.attachid == el.attachid)) {
                  // 选中
                  this.defaultKeys.push(item.key)
                }
              })
            }
          }
        })
      }
    },
    onExpand (expandedKeys) {
      console.log("选择的key", expandedKeys)
      this.expandedKeys = expandedKeys
      // this.autoExpandParent = false
    },
    onCheck (checkedKeys, info) {
      this.checkList = checkedKeys
      console.log('onCheck', checkedKeys, info)
    },
    onSelect (selectedKeys, info) {
      this.selectKey = info.node.$options.propsData.eventKey
      if (this.selectKey) {
        this.findTreeDataByKey(this.selectKey)
      }
      console.log('selected', selectedKeys, info)
    },

    searchTreeNode (e) {
      const value = e.target.value
      this.filter(this.treeData, value)
      if (value == '') {
        this.treeData = JSON.parse(JSON.stringify(this.cloneTreeData)) //cloneTreeData 接口返回深拷贝的数据
      }
    },
    filter (nodes, query) {
      // 条件就是节点的title过滤关键字
      let predicate = function (node) {
        if (node.title.indexOf(query) > -1) {
          return true
        } else {
          return false
        }
      }
      if (!(nodes && nodes.length)) {
        return []
      }
      let newChildren = []
      for (let node of nodes) {
        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        if (predicate(node)) {
          newChildren.push(node)
          node.children = this.filter(node.children, query)
        } else {
          newChildren.push(...this.filter(node.children, query))
        }
      }
      this.treeData = newChildren //this.treeData接口返回的数组
      return newChildren.length ? newChildren : []
    },

    findLevel3Data () {
      let treeFileData = []
      if (this.treeData[0].children && this.treeData[0].children.length > 0) {
        this.treeData[0].children.forEach(child => {
          if (child.children) {
            child.children.forEach(innerChild => {
              if (innerChild.children) {
                innerChild.children.forEach(lasetChild => {
                  if (lasetChild.level == 3) {
                    treeFileData.push(lasetChild)
                  }
                })
              }
            })
          }
        })
      }
      this.treeLevel3Data = treeFileData
    },
    findTreeDataByKey (key) {
      // 查找全部的级别为3层的数据
      let fileItem = null
      if (this.treeLevel3Data == null || this.treeLevel3Data.length == 0) {
        this.findLevel3Data()
      }
      if (this.treeLevel3Data && this.treeLevel3Data.length > 0) {
        this.treeLevel3Data.forEach(item => {
          if (item.key == key) {
            fileItem = item
          }
        })
        if (fileItem != null && fileItem != undefined) {
          this.filePreview(fileItem)
        }
      }
    },
    filePreview (selectFile) {
      if (selectFile) {
        console.log('文件预览', selectFile)
        window.open(kkfilePreview(selectFile.document.file.path))
      } else {
        this.$message.error('未选择文书类型')
      }
    },

    setSlot (treeData, expandedKeys) {
      console.log('树形数据', treeData)
      treeData.disableCheckbox = true
      if (treeData.children && treeData.children.length > 0) {
        treeData.children.forEach(child => {
          if (child.level == 0 || child.level == 1) {
            child.scopedSlots = { title: 'custom' }
            child.disableCheckbox = true
            expandedKeys.push(child.key)
          } else if (child.level == 2) {
            child.scopedSlots = { title: 'custom' }
            child.disableCheckbox = true
            if (child.children && child.children.length > 0) {
              expandedKeys.push(child.key)
            }
          } else {
            child.scopedSlots = { title: 'custom' }
            child.disableCheckbox = false
          }
          if (child && child.children) {
            this.setSlot(child, expandedKeys)
          }
        })
      }
    },
    queryDocumentTree () {
      this.spinning = true
      getDocumentTree(this.applyid)
        .then(res => {
          if (res.code == 0) {
            this.treeData = res.data
            // 对数据进行slot的设置
            this.treeData[0].scopedSlots = { title: 'custom' }
            this.expandedKeys = ['root']
            // if (this.treeData && this.treeData[0]) {
            //   let firstLevelChilds = this.treeData[0]
            //   if (firstLevelChilds && firstLevelChilds.length > 0) {
            //     firstLevelChilds.forEach(child => {
            //       this.expandedKeys.push[child.key]
            //     })
            //   }
            // }
            this.setSlot(this.treeData[0], this.expandedKeys)
            console.log('选中的数据', this.expandedKeys)
            this.modalVisible = true
            this.findLevel3Data()
            this.getCheckedData()
            //搜索框的值为空时，重新赋值
            this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
          } else {
            this.$message.error('查询文件数据错误，请核对案号是否正确')
            this.modalVisible = false
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
      /**
     * 确定保存导入数据
     */
     importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      let files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.uploadMaterial(importFileList)
    },
    /**
     * 上传材料的接口
     */
    uploadMaterial (importFileList) {
      let param = {
        applyid: this.applyid,
        mattype: this.selectBusiType,
        userId: this.currentUser.userId,
        userName: this.currentUser.fullname
      }
      this.spinning = true
      this.$refs.multiUploadBasic.loading = true
      saveMaterialArrive(param, importFileList)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error(res.msg)
          } else {
            let fileItemList = res.data
            if (fileItemList && fileItemList.length > 0) {
              fileItemList.forEach(file => {
                let nodeData = {
                  children: [],
                  disableCheckbox: false,
                  document: JSON.parse(JSON.stringify(file)),
                  isSend: false,
                  key: file.id,
                  level: 3,
                  title: file.file.filename
                }
                this.addNewFile(this.selectBusiType, nodeData)
              })
            }
            this.$message.info('上传文件成功')
            this.$refs.multiUploadBasic.handleCancel()
          }
        })
        .catch(err => {
          console.log(err, '上传数据失败')
        })
        .finally(() => {
          this.spinning = false
          this.$refs.multiUploadBasic.loading = false
        })
    },
    uploadModalShow (info) {
      this.selectBusiType = info.eventKey
      this.$refs.multiUploadBasic.importVisible = true
    },

    addNewFile (mattype, nodeData) {
      // 遍历二级节点
      if (this.treeData[0] && this.treeData[0].children && this.treeData[0].children.length > 0) {
        this.treeData[0].children.forEach(child => {
          if (child && child.children) {
            child.children.forEach(node => {
              if (node.key == mattype) {
                nodeData.scopedSlots = { title: 'custom' }
                if (node.children) {
                  node.children.push(nodeData)
                } else {
                  node.children = []
                  node.children.push(nodeData)
                }
              }
            })
          }
        })
      }
      this.findLevel3Data()
      this.getCheckedData()
      this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
    },
    deleteFile (item) {
      this.$confirm({
        title: '是否删除该数据？',
        onOk: () => {
          this.spinning = true
          deleteMaterial({ materialId: item.key }).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功')
              this.queryDocumentTree()
            } else {
              this.$message.error(res.msg)
              this.spinning = false
            }
          })
        }
      })
    }
  }
}
</script>

        
<style lang="less" scoped>
.but_type {
  color: #1890ff !important;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}
// 当前隐藏禁用的树多选框

::v-deep .tree-div-select-hidden {
  .ant-tree-checkbox-disabled {
    display: none;
  }
}

.file-tree-content {
  font-size: 14px;
  color: #0072c6 !important;
}

.hover-delete {
  display: inline-block;
  padding-left: 20px;
  color: red !important;
}

::v-deep .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}
/* 禁用状态文字 */
::v-deep li.ant-tree-treenode-disabled > .ant-tree-node-content-wrapper span {
  color: #2c2c2c;
}

.ant-tree-title-margin {
  margin-left: 20px;
}

.custom-icon-open,
.custom-icon-fold,
.icon-add {
  color: #fff;
  background-color: #0072c6;
  font-weight: 800;
  font-size: 16px !important;
}
/* 用文字图标覆盖展开图标实现效果 */
.custom-icon-open,
.custom-icon-fold {
  width: 20px;
  height: 20px;
  margin-left: -26px;
}
/* 文字偏移补充图标间距 */
.node_text {
  margin-left: -26px;
}
/* 折叠样式 */
.custom-icon-fold {
  background-color: #09c89f;
}
/* 自定义展开图标 */
.icon-add {
  width: 24px;
  height: 24px;
  opacity: 0;
}
::v-deep .ant-scroll-number-only {
  color: #fff !important;
}
</style>

